const express = require('express')
const cors = require('cors')
const app = express()

// 日志中间件
const logger = require('morgan');
app.use(logger('dev'))
// 解决跨域问题
app.use(cors())
// 静态资源中间件
app.use('/static', express.static('./static'))
// 配置解析 application/json 格式数据的中间件
app.use(express.json())
// 配置解析 application/x-www-form-urlencoded 格式数据的中间件
app.use(express.urlencoded({extended: false}))

// 自定义global中间件 多个中间件之间，req和res为同一个对象
app.use((req, res, next) => {
    console.log('我是一个global中间件', Date.now())
    req.timestamp = Date.now()
    next();
})
// 路由
const userRouter = require('./router/user');
const mqttRouter = require('./router/mqtt');
const transferRouter = require('./router/transfer');
const qrcodeRouter = require('./router/qrcode');
app.use('/api', userRouter)
app.use('/mqtt', mqttRouter)
app.use('/transfer', transferRouter)
app.use('/qrcode', qrcodeRouter)

// 错误级别中间件
app.use((err, req, res, next) => {
    console.log('我是一个global 错误处理中间件', err)
    next();
})

//服务端口
const port = 80
app.listen(port, () => {
    console.log(`server run at http://localhost:${port}`)
})
